{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "C:\\Users\\Administrator\\Anaconda3\\lib\\requests\\__init__.py:80: RequestsDependencyWarning: urllib3 (1.25.11) or chardet (3.0.4) doesn't match a supported version!\n",
      "  RequestsDependencyWarning)\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "matchzoo version 1.0.2\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import numpy as np\n",
    "import pandas as pd\n",
    "import mzcn as mz\n",
    "print('matchzoo version', mz.__version__)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "`classification_task` initialized with metrics [accuracy]\n"
     ]
    }
   ],
   "source": [
    "classification_task = mz.tasks.Classification(num_classes=2)\n",
    "classification_task.metrics = ['acc']\n",
    "print(\"`classification_task` initialized with metrics\", classification_task.metrics)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "def load_data(tmp_data,tmp_task):\n",
    "\tdf_data = mz.pack(tmp_data,task=tmp_task)\n",
    "\treturn df_data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "data loading ...\n",
      "data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`\n"
     ]
    }
   ],
   "source": [
    "print('data loading ...')\n",
    "##数据集，并且进行相应的预处理\n",
    "train=pd.read_csv('./data/train_data.csv').sample(100)\n",
    "dev=pd.read_csv('./data/dev_data.csv').sample(50)\n",
    "test=pd.read_csv('./data/test_data.csv').sample(30)\n",
    "train_pack_raw = load_data(train,classification_task)\n",
    "dev_pack_raw = load_data(dev,classification_task)\n",
    "test_pack_raw=load_data(test,classification_task)\n",
    "print('data loaded as `train_pack_raw` `dev_pack_raw` `test_pack_raw`')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "停用表配置成功\n"
     ]
    }
   ],
   "source": [
    "import os\n",
    "folder=mz.__path__[0]+'\\\\preprocessors\\\\units\\\\'\n",
    "file=folder+'stopwords.txt'\n",
    "if not os.path.exists(file):\n",
    "    print('请将stopwords.txt放置在'+folder+'下面'+'否则会报错')\n",
    "else:\n",
    "    print('停用表配置成功')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "187"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gc\n",
    "gc.collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "preprocessor = mz.models.ESIM.get_default_preprocessor()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval:   0%| | 0/95 [00:00<?, ?it/s]Building prefix dict from the default dictionary ...\n",
      "Loading model from cache C:\\Users\\ADMINI~1\\AppData\\Local\\Temp\\jieba.cache\n",
      "Loading model cost 1.215 seconds.\n",
      "Prefix dict has been built succesfully.\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 95/95 [00:01<00:00, 53.52it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 98/98 [00:00<00:00, 187.84it/s]\n",
      "Processing text_right with append: 100%|████████████████████████████████████████████| 98/98 [00:00<00:00, 48986.03it/s]\n",
      "Building FrequencyFilter from a datapack.: 100%|████████████████████████████████████| 98/98 [00:00<00:00, 16345.56it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 98/98 [00:00<00:00, 49126.54it/s]\n",
      "Processing text_left with extend: 100%|█████████████████████████████████████████████| 95/95 [00:00<00:00, 47599.91it/s]\n",
      "Processing text_right with extend: 100%|████████████████████████████████████████████| 98/98 [00:00<00:00, 12260.75it/s]\n",
      "Building Vocabulary from a datapack.: 100%|██████████████████████████████████████| 989/989 [00:00<00:00, 994287.31it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 95/95 [00:00<00:00, 178.67it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 98/98 [00:00<00:00, 200.94it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 98/98 [00:00<00:00, 24444.95it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 95/95 [00:00<00:00, 47520.44it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 98/98 [00:00<00:00, 98927.03it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 95/95 [00:00<00:00, 95074.89it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 98/98 [00:00<00:00, 49926.13it/s]\n",
      "Processing text_left with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 48/48 [00:00<00:00, 191.35it/s]\n",
      "Processing text_right with chain_transform of ChineseRemoveBlack => ChineseSimplified => ChineseEmotion => IsChinese => ChineseStopRemoval => ChineseTokenizeDemo => Tokenize => Lowercase => PuncRemoval: 100%|█| 50/50 [00:00<00:00, 187.37it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 50/50 [00:00<00:00, 24771.46it/s]\n",
      "Processing text_left with transform: 100%|██████████████████████████████████████████| 48/48 [00:00<00:00, 24039.00it/s]\n",
      "Processing text_right with transform: 100%|█████████████████████████████████████████| 50/50 [00:00<00:00, 25019.71it/s]\n",
      "Processing length_left with len: 100%|██████████████████████████████████████████████| 48/48 [00:00<00:00, 48465.72it/s]\n",
      "Processing length_right with len: 100%|█████████████████████████████████████████████| 50/50 [00:00<00:00, 25040.62it/s]\n"
     ]
    }
   ],
   "source": [
    "train_pack_processed = preprocessor.fit_transform(train_pack_raw)\n",
    "dev_pack_processed = preprocessor.transform(dev_pack_raw)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'embedding_input_dim': 338,\n",
       " 'filter_unit': <mzcn.preprocessors.units.frequency_filter.FrequencyFilter at 0x275b536a128>,\n",
       " 'vocab_size': 338,\n",
       " 'vocab_unit': <mzcn.preprocessors.units.vocabulary.Vocabulary at 0x275b58002b0>}"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "preprocessor.context"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "# glove_embedding = mz.datasets.embeddings.load_glove_embedding(dimension=100)\n",
    "# term_index = preprocessor.context['vocab_unit'].state['term_index']\n",
    "# embedding_matrix = glove_embedding.build_matrix(term_index)\n",
    "# l2_norm = np.sqrt((embedding_matrix * embedding_matrix).sum(axis=1))\n",
    "# embedding_matrix = embedding_matrix / l2_norm[:, np.newaxis]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "trainset = mz.dataloader.Dataset(\n",
    "    data_pack=train_pack_processed,\n",
    "    mode='point'\n",
    ")\n",
    "devset = mz.dataloader.Dataset(\n",
    "    data_pack=dev_pack_processed,\n",
    "    mode='point'\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "padding_callback = mz.models.ESIM.get_default_padding_callback()\n",
    "\n",
    "trainloader = mz.dataloader.DataLoader(\n",
    "    dataset=trainset,\n",
    "    stage='train',\n",
    "    callback=padding_callback\n",
    ")\n",
    "devloader = mz.dataloader.DataLoader(\n",
    "    dataset=devset,\n",
    "    stage='dev',\n",
    "    callback=padding_callback\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "ESIM(\n",
      "  (embedding): Embedding(338, 100, padding_idx=0)\n",
      "  (rnn_dropout): RNNDropout(p=0.2, inplace=False)\n",
      "  (input_encoding): StackedBRNN(\n",
      "    (rnns): ModuleList(\n",
      "      (0): LSTM(100, 100, bidirectional=True)\n",
      "    )\n",
      "  )\n",
      "  (attention): BidirectionalAttention()\n",
      "  (projection): Sequential(\n",
      "    (0): Linear(in_features=800, out_features=200, bias=True)\n",
      "    (1): ReLU()\n",
      "  )\n",
      "  (composition): StackedBRNN(\n",
      "    (rnns): ModuleList(\n",
      "      (0): LSTM(200, 100, bidirectional=True)\n",
      "    )\n",
      "  )\n",
      "  (classification): Sequential(\n",
      "    (0): Dropout(p=0.2, inplace=False)\n",
      "    (1): Linear(in_features=800, out_features=200, bias=True)\n",
      "    (2): Tanh()\n",
      "    (3): Dropout(p=0.2, inplace=False)\n",
      "  )\n",
      "  (out): Linear(in_features=200, out_features=2, bias=True)\n",
      ")\n",
      "Trainable params:  757802\n"
     ]
    }
   ],
   "source": [
    "model = mz.models.ESIM()\n",
    "\n",
    "model.params['task'] = classification_task\n",
    "# model.params['embedding'] = embedding_matrix #这里是当加载glove等模型时取消该行注释\n",
    "#设置embedding系数\n",
    "model.params[\"embedding_output_dim\"]=100\n",
    "model.params[\"embedding_input_dim\"]=preprocessor.context[\"embedding_input_dim\"]\n",
    "model.params['mask_value'] = 0\n",
    "model.params['dropout'] = 0.2\n",
    "model.params['hidden_size'] = 200\n",
    "model.params['lstm_layer'] = 1\n",
    "\n",
    "model.build()\n",
    "\n",
    "print(model)\n",
    "print('Trainable params: ', sum(p.numel() for p in model.parameters() if p.requires_grad))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": [
    "optimizer = torch.optim.Adam(model.parameters(),lr=1e-5)\n",
    "\n",
    "trainer = mz.trainers.Trainer(\n",
    "    model=model,\n",
    "    optimizer=optimizer,\n",
    "    trainloader=trainloader,\n",
    "    validloader=devloader,\n",
    "    validate_interval=None,\n",
    "    epochs=5\n",
    ")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "726be29dbe954dc3ac6db0ba1c97fc21",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=3), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-3 Loss-0.696]:\n",
      "  Validation: accuracy: 0.2\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "72c0dbb059fd46979fefd94c33017ed0",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=3), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-6 Loss-0.695]:\n",
      "  Validation: accuracy: 0.6286\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "519b8dc8286d434d95bba50294f75ec7",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=3), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-9 Loss-0.692]:\n",
      "  Validation: accuracy: 0.8571\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "25aba4b9672b4fcdaa75c89f91e4d7b1",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=3), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-12 Loss-0.688]:\n",
      "  Validation: accuracy: 0.8571\n",
      "\n"
     ]
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "82cf2888d592403fb3e5663fbf1ea57a",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "HBox(children=(IntProgress(value=0, max=3), HTML(value='')))"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[Iter-15 Loss-0.687]:\n",
      "  Validation: accuracy: 0.8571\n",
      "\n",
      "Cost time: 8.31123399734497s\n"
     ]
    }
   ],
   "source": [
    "trainer.run()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "416"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import gc\n",
    "gc.collect()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {
    "collapsed": true
   },
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
